sink("run.log", split = TRUE)
cat("Starting replication at: ", Sys.time(), "\n\n")

# Storage for runtime
script_times <- list()

# Define a helper function to time scripts
run_with_timer <- function(script_path) {
  cat("Running:", script_path, "\n")
  start_time <- Sys.time()
  source(script_path)
  end_time <- Sys.time()
  elapsed <- as.numeric(difftime(end_time, start_time, units = "secs"))
  cat("Completed:", script_path, "in", elapsed, "seconds\n\n")
  
  # Save elapsed time
  script_times[[script_path]] <<- elapsed
}

# Run analysis scripts with timers
run_with_timer("code/helper_analysis.R")
run_with_timer("code/classification_svm.R") # you can comment (#) this for faster reproduction of graphs and figures
run_with_timer("code/prediction_svm.R")
run_with_timer("code/analysis_main_labeled.R")
run_with_timer("code/analysis_main_functional_tests.R")
run_with_timer("code/analysis_main_partisan_differences_GER.R")
run_with_timer("code/analysis_main_partisan_differences_USA.R")

cat("Replication completed at: ", Sys.time(), "\n\n")

# Print summary overview at the end
cat("===== Runtime Summary (seconds) =====\n")
for (script in names(script_times)) {
  cat(script, ":", script_times[[script]], "seconds\n")
}
cat("Total runtime:", sum(unlist(script_times)), "seconds\n")
sink()

## Creating a renv.lock file to document all packages used in the computational workflow
renv::snapshot()
